<div class="formLeftTem layui-collapse" lay-accordion>

</div>

<script>

    layui.use(['form'], function () {

        // -----常量声明----------
        var $ = layui.$,
            element = layui.element,
            setter = layui.setter,
            form = layui.form,
            commons = layui.commons,
            formId = '${formDefId}' || '',
            viewMould = serverPath.formPath + '/form/formDef/view/formDesign/moulds/',
            loadReq = 'request',
            temSpace = '.temSpace',
            suffix = '',
            fiedldName = 'name',
            temType = function (params) {
                return params === 1 ? 'template/text' :
                    params === 2 ? 'template/textArea':
                        params === 15 ? 'template/date':
                            params === 11 ? 'template/select':
                                params === 14 ? 'template/radioOption':
                                    params === 13 ? 'template/checkOption':
                                        params === 10 ? 'template/richText':
                                            params === 3 ? 'template/dataLexi':
                                                params === 9 ? 'template/uploadFile':
                                                    params === 22 ? 'template/uploadImg':
                                                        params === 16 ? 'template/hideField':
                                                            (params === 8 || params === 4 || params === 17 || params === 5 || params === 18 || params === 6 || params === 19 || params === 7) ? 'template/selector':
                                                                '';
            };


        // --- 通用方法 -----

        // 延迟执行拆解 初始化操作
        function timeoutLoad(name,item,obj,star) {
            var _elem = $(name);
            _elem.load(setter.views + viewMould + item + '/index' + suffix, function () {
                _elem.find(temSpace).parent().attr(loadReq, item);
                if (obj) {
                    _elem.find('.dragRemove').attr('dragItemid', obj.fieldId);
                    _elem.children('span').html(obj.fieldDesc);

                    switch (obj.controlType) {
                        // 文本
                        case 1 :
                            _elem.find('.temSpace .textLabel').html(obj.fieldDesc);
                            _elem.find('.temSpace .textInput').attr(fiedldName, star + obj.fieldName);
                            var verify = [];
                            if (obj.fieldType === 'number') {
                                var ctlProperty = JSON.parse(obj.ctlProperty);
                                var isShowComdify = ctlProperty.isShowComdify;
                                var coinValue = ctlProperty.coinValue; //货币值￥/$
                                if (isShowComdify === 0) {
                                    verify.push('number');
                                }
                                if (isShowComdify === 1 && coinValue == "") { //千分位
                                    verify.push('numberThousands');
                                }
                                if (isShowComdify === 1 && coinValue != "") { //货币
                                    verify.push('numberMoney');
                                }
                                if (obj.decimalLen > 0) {
                                    verify.push('customFloat');
                                    _elem.find('.temSpace .textInput').attr('customDecimal', obj.decimalLen);
                                    _elem.find('.temSpace .textInput').attr('customInt', obj.intLen);
                                }
                            }
                            if (!!obj.validRule) {
                                verify.push(obj.validRule);
                            }
                            if (obj.isRequired === 1) {
                                verify.push('required');
                            }
                            //判断小数位数是否大于0，如果大于0，则加上小数点所占空间
                            if (obj.charLen || obj.intLen) {
                                var numberMaxLength = parseInt(obj.intLen, 10) + (parseInt(obj.decimalLen, 10) ? (parseInt(obj.decimalLen, 10) + 1) : parseInt(obj.decimalLen, 10));
                                _elem.find('.temSpace .textInput').attr('maxlength', obj.charLen || numberMaxLength);
                            }
                            if (verify.length > 0) {
                                _elem.find('.temSpace .textInput').attr('lay-verify', verify.join('|'));
                            }

                            break;
                        // 文本域
                        case 2 :
                            _elem.find('.temSpace .textAreaLabel').html(obj.fieldDesc);
                            _elem.find('.temSpace .textAreaInput').attr(fiedldName, star + obj.fieldName);

                            var verify = []
                            if (obj.isRequired === 1) {
                                verify.push('required');
                            }
                            if (obj.charLen || obj.intLen) {
                                _elem.find('.temSpace .textAreaInput').attr('maxlength', obj.charLen || obj.intLen);
                            }
                            if (verify.length > 0) {
                                _elem.find('.temSpace .textAreaInput').attr('lay-verify', verify.join('|'));
                            }

                            break;
                        // 日期
                        case 15 :
                            _elem.find('.temSpace .dateLabel').html(obj.fieldDesc);
                            _elem.find('.temSpace .dateInput').attr(fiedldName, star + obj.fieldName);
                            _elem.find('.temSpace .dateInput').attr('displaydate', obj.propertyMap.displayDate);
                            _elem.find('.temSpace .dateInput').attr('format', obj.propertyMap.format);
                            _elem.find('.temSpace .dateInput').attr('datetype', obj.propertyMap.dateType);
                            break;
                        // 下拉
                        case 11 :
                            _elem.find('.temSpace .selectLabel').html(obj.fieldDesc);
                            _elem.find('.temSpace .temSelectCont').attr(fiedldName, star + obj.fieldName);
                            var verify = []
                            if (obj.isRequired === 1) {
                                verify.push('required');
                            }
                            if (verify.length > 0) {
                                _elem.find('.temSpace .temSelectCont').attr('lay-verify', verify.join('|'));
                            }
                            var options = JSON.parse(obj.options);
                            for (var i = 0; i < options.length; i++) {
                                _elem.find('.temSpace .temSelectCont').append('<option value=' + options[i].key + '>' + options[i].value + '</option>');
                            }

                            break;

                        // 单选
                        case 14 :
                            _elem.find('.temSpace .radioOptionLabel').html(obj.fieldDesc);
                            _elem.find('.temSpace .radioOptionCont').attr(fiedldName, star + obj.fieldName);
                            var options = JSON.parse(obj.options);
                            _elem.find('.temSpace .radioOptionCont > div').html('');
                            for (var i = 0; i < options.length; i++) {
                                _elem.find('.temSpace .radioOptionCont > div').append('<input type="radio" name=' + obj.fieldName + ' value=' + options[i].key + ' title=' + options[i].value + '>');
                            }

                            break;

                        // 复选
                        case 13 :
                            _elem.find('.temSpace .checkOptionLabel').html(obj.fieldDesc);
                            _elem.find('.temSpace .checkOptionCont').attr(fiedldName, star + obj.fieldName);
                            var options = JSON.parse(obj.options);
                            _elem.find('.temSpace .checkOptionCont > div').html('');
                            for (var i = 0; i < options.length; i++) {
                                _elem.find('.temSpace .checkOptionCont > div').append('<input lay-skin="primary" type="checkbox" name="' + obj.fieldName + '[' + options[i].key + ']" value=' + options[i].key + ' title=' + options[i].value + '>');
                            }

                            break;

                        // 富文本

                        case 10 :
                            _elem.find('.temSpace .richTextLabel').html(obj.fieldDesc);
                            _elem.find('.temSpace .richTextCont').attr(fiedldName, star + obj.fieldName);

                            break;

                        // 数据词典
                        case 3 :
                            _elem.find('.temSpace .dataLexiLabel').html(obj.fieldDesc);
                            _elem.find('.temSpace .dataLexiTree').attr('dicttype', obj.dictType);
                            _elem.find('.temSpace .dataLexiVal').attr(fiedldName, star + obj.fieldName);
                            break;

                        // 文件上传

                        case 9 :
                            _elem.find('.temSpace .uploadFileLabel').html(obj.fieldDesc);
                            _elem.find('.temSpace .uploadFileCont .uploadFileBtn').attr('fileTypes', obj.fileTypes);
                            _elem.find('.temSpace .uploadFileCont .uploadFileList').attr(fiedldName, star + obj.fieldName);
                            break;

                        // 图片上传

                        case 22 :
                            _elem.find('.temSpace .uploadImgLabel').html(obj.fieldDesc);
                            _elem.find('.temSpace .uploadImgCont .uploadImgList').attr(fiedldName, star + obj.fieldName);
                            break;

                        // 隐藏域
                        case 16 :
                            _elem.find('.temSpace .hideFieldLabel').html(obj.fieldDesc);
                            _elem.find('.temSpace .hideFieldInput').attr(fiedldName, star + obj.fieldName);
                            break;
                        // 选择器
                        case 8 :
                        case 4 :
                        case 17 :
                        case 5 :
                        case 18 :
                        case 6 :
                        case 19 :
                        case 7 :
                            _elem.find('.temSpace .selectorLabel').html(obj.fieldDesc);
                            _elem.find('.temSpace .selectorBtn').attr('typeid', obj.controlType);
                            _elem.find('.temSpace .selectorInput').attr(fiedldName, star + obj.fieldName);

                            break;
                    }
                    timers(function () {
                        dragCase.init()
                    })
                }
            });
        }



// ------start---------
        // data解析
        $.ajax({
            url: serverPath.formPath + setter.formLinkPath +"printTemplate/edit",
            type: "GET",
            contentType: 'application/json',
            dataType: 'json',
            data:{
                id: printTemplateId,
                formKey:formKey
            },
            success: function(result) {
                // 组合数据
                var data = result.data;
                if(!data.mainTable){ return false }
                $('#dragDiv').html(decodeURI(decodeURIComponent( data.printTemplate.html)));

                // 主表数据
                var main = data.mainTable,
                    // 主表数据list
                    mainList = main.tableFields,
                    // 子表长度
                    subCount = data.subCount,
                    // 容器字符串结构
                    strCont = function(str,num){
                        return ('<div class="layui-colla-item">'
                            +'<h2 class="layui-colla-title">'
                            +(num === '1' ? '<span style="color:#f00">*</span>' : '')
                            + str
                            +'</h2>'
                            +'<ul class="dragLeftCont mainTabForm dragSourceLeft layui-colla-content '
                            + (num === '1' ? 'layui-show' : '')
                            +'">'
                            +'</ul></div>')
                    },
                    mainTabStr = function(tabRow,tabCol,dragitemid,modeType,tableName){
                        return (
                            '<div class="temCont">' +
                            '<div class="dragOpt">' +
                            '<i class="layui-icon dragMoveBtn layui-icon-list"></i>' +
                            '<i class="layui-icon dragRemove layui-icon-delete" dragitemid="'+(dragitemid||'')+'"></i>' +
                            '</div>' +
                            '<div class="dragGather" request="template/table">' +
                            '<div class="">' +
                            (modeType?'<a modetype="'+(modeType||'')+'" class="addFormTr layui-btn layui-btn-sm">新增</a>': '') +
                            '<table class="temTable '+tableName+' '+(dragitemid ? 'subFormTable':'tableExcel')+'">' +
                            '<tbody request="template/table">' +
                            function () {
                                var strTr = '';
                                for(var i=0;i<tabRow;i++){
                                    strTr += '<tr class="temSpace" request="template/table">' +
                                        function () {
                                            var strTd = '';
                                            for(var j = 0; j<tabCol; j++ ){
                                                strTd += '<td class="'+(dragitemid ? '':'dragInfo')+' temSpace"></td>'
                                            }
                                            return strTd;
                                        }()+
                                        '</tr>'
                                }
                                return strTr;
                            }() +
                            '</tbody>' +
                            '</table>' +
                            '</div>' +
                            '</div>' +
                            '</div>'
                        )
                    },
                    templatesId = data.printTemplate.id.split(';');
                $('.form-props-info').attr('tableid',main.tableId);
                $('.form-props-info').attr('formid',formId);
                if(!data.printTemplate.html){
                    var rows = parseInt(templatesId[0],10),
                        strCon = mainTabStr(rows,rows,'','');
                    $('#dragDiv').html(strCon);
                }
                $('.formLeftTem').html(strCont(main.tableName,'1'));
                $('.dragLeftCont').html('');

                if(null != data.printTemplate.html){
                    $('#dragDiv').html(decodeURI(decodeURIComponent(data.printTemplate.html)));
                }
                //回填数据
                $("#templateName").val(data.printTemplate.templateName);
                if(data.printTemplate.alias != null && data.printTemplate.alias != ""){
                    $("#alias").val(data.printTemplate.alias);
                }else{
                    $.ajax({
                        url: serverPath.formPath + "/form/table/getFieldKey",
                        data: ({fieldDesc: data.printTemplate.templateName}),
                        dataType:'json',
                        success: function (obj) {
                            if (commons._filterRecord(obj)) {
                                $("#alias").val(obj.data);
                            }
                        }
                    });
                }
                if(data.printTemplate.isPrintInFinish == '1'){
                    $("input[name=isPrintInFinish][value='1']").attr("checked", true);
                }else{
                    $("input[name=isPrintInFinish][value='0']").attr("checked", true);
                }
                if(data.printTemplate.isPrintInForm == '1'){
                    $("input[name=isPrintInForm][value='1']").attr("checked", true);
                }else{
                    $("input[name=isPrintInForm][value='0']").attr("checked", true);
                }
                form.render();

                // 主表解析
                for(var i = 0; i < mainList.length; i++){
                    var type = temType(mainList[i].controlType);
                    $('.mainTabForm').append('<li></li>');
                    var star = 'm:'+main.tableName+':';
                    timeoutLoad('.mainTabForm > li:eq('+i+')',type, mainList[i],star);
                }

                // 子表解析
                // for(var j = 1; j < subCount+1; j++){
                //   var subInfo =  data['subTable'+j],
                //   subList = subInfo.tableFields;
                //   $('.formLeftTem').append(strCont(subInfo.tableName));
                //   for( var k = 0; k<subList.length; k++){
                //     var type = temType(subList[k].controlType);
                //     $('.dragLeftCont:eq('+j+')').append('<li></li>');
                //     var star = 's:'+subInfo.tableName+':';
                //     timeoutLoad('.dragLeftCont:eq('+j+')',k,type, subList[k],star);
                //   }
                // }

                if(subCount > 0){
                    $('.formLeftTem').append('<ul class="dragLeftCont subTabForm dragSourceLeft"></ul>');
                    var temTag = function (strTag) {
                        return ('<div class="temCont">' +
                            '<div class="dragOpt">' +
                            '<i class="layui-icon dragMoveBtn layui-icon-list"></i>' +
                            '<i class="layui-icon dragRemove layui-icon-delete"></i>' +
                            '</div>' +
                            '<div class="dragGather" request="template/tag">' +
                            '<div class="temSpace temSpaceCss">' +
                            '<div class="temTag">' +
                            strTag +
                            '</div></div></div></div>')
                    };
                    for(var j = 0; j < subCount; j++){
                        var subInfo =  data['subTable'+(j+1)],
                            subList = subInfo.tableFields,
                            modeType = templatesId[1]||'2';
                        var subStr = '<li>' +
                            '<span>'+subInfo.tableName+'</span>' +
                            '<div class="dragSourceInfo">' +
                            mainTabStr(3,subList.length+2,subInfo.tableId,modeType,subInfo.tableName) +
                            '</div>' +
                            '</li>';
                        $('.subTabForm').append(subStr);
                        for(var s=0;s<subList.length+2;s++){
                            var subName = '.subTabForm > li:eq('+j+') .temTable tr:eq(0) td:eq('+s+')',
                                subContTem = '.subTabForm > li:eq('+j+') .temTable tr:eq(1) td:eq('+s+')',
                                subCont = '.subTabForm > li:eq('+j+') .temTable tr:eq(2) td:eq('+s+')';
                            if(s === 0){
                                $(subName).html(temTag('序号'));
                                $(subContTem).html(temTag('0'));
                                $(subCont).html(temTag('1'));
                            } else if(s===subList.length+1){
                                $(subName).html(temTag('管理'));
                                var opt = function(){
                                    return  (modeType === '2' ?
                                            '<a class="layui-btn layui-btn-sm subDeleteTr">删除</a>'
                                            :
                                            '<a class="layui-btn layui-btn-sm subUpdateTr">修改</a>' +
                                            '<a class="layui-btn layui-btn-sm subDeleteTr">删除</a>'
                                    )
                                };
                                $(subCont).html(opt);
                                $(subContTem).html(opt);
                                $(subName).addClass('subOptState');
                                $(subCont).addClass('subOptState');
                                $(subContTem).addClass('subOptState');
                            } else{
                                var type = temType(subList[s-1].controlType),
                                    star = 's:'+subInfo.tableName+':';
                                $(subName).html(temTag(subList[s-1].fieldDesc));
                                timeoutLoad(subCont,type, subList[s-1],star);
                                timeoutLoad(subContTem,type, subList[s-1],star);
                                if(subList[s-1].listShow === 0){
                                    $(subName).addClass('subFieldState');
                                    $(subCont).addClass('subFieldState');
                                    $(subContTem).addClass('subFieldState');
                                }
                                if(subList[s-1].dialogShow === 0){
                                    $(subName).addClass('subDialogShowState');
                                    $(subCont).addClass('subDialogShowState');
                                    $(subContTem).addClass('subDialogShowState');
                                }
                            }
                            $('.subTabForm > li:eq('+j+') .temTable tr:eq(1)').addClass('subContTem');
                        }

                    }
                }

                // layui构建节点初始化
                element.render();
            }

        })





    })
</script>